/*
** delete.c for minishell2 in /home/lingla_j/work/tutorat/env
** 
** Made by julien linglain
** Login   <lingla_j@epitech.net>
** 
** Started on  Tue Feb 28 15:10:51 2012 julien linglain
** Last update Sun Mar  4 10:35:47 2012 julien linglain
*/

#include <stdlib.h>
#include <string.h>
#include "mysh.h"

int		delete_middle_node(t_list *env, char *key)
{
  t_node	*ptr;
  t_node	*tmp;

  ptr = env->start;
  tmp = NULL;
  while (my_strcmp(ptr->next->key, key) != 0)
    ptr = ptr->next;
  tmp = ptr->next;
  ptr->next = tmp->next;
  free(tmp->key);
  free(tmp->value);
  free(tmp);
  env->size--;
  return (0);
}

int		delete_last_node(t_list *env, char *key)
{
  t_node	*ptr;

  ptr = env->start;
  while (my_strcmp(ptr->next->key, key) != 0 && ptr->next != NULL)
    ptr = ptr->next;
  env->end = ptr;
  free(ptr->next->key);
  free(ptr->next->value);
  free(ptr->next);
  env->size--;
  env->end->next = NULL;
  return (0);
}

int		delete_first_node(t_list *env)
{
  t_node	*ptr;

  ptr = env->start;
  env->start = env->start->next;
  free(ptr->key);
  free(ptr->value);
  env->size--;
  free(ptr);
  return (0);
}

int		check_node(t_list *env, char *key)
{
  t_node	*ptr;

  ptr = env->start;
  while (ptr != NULL)
    {
      if (my_strcmp(ptr->key, key) == 0)
        return (1);
      ptr = ptr->next;
    }
  return (0);
}

int		delete_node(t_list *env, char *key)
{
  t_node        *ptr;

  ptr = env->start;
  if (!check_node(env, key))
    {
      my_puterror("Key not found.\n");
      return (EXIT_FAILURE);
    }
  if (check_exception(env, key) == 1)
    return (EXIT_SUCCESS);
  while (my_strcmp(ptr->key, key) != 0)
    ptr = ptr->next;
  if (ptr->next == NULL)
    delete_last_node(env, key);
  else if (ptr == env->start)
    delete_first_node(env);
  else
    delete_middle_node(env, key);
  return (0);
}
